import html2canvas from "html2canvas";
import topicDetails from "./component/topicDetails";
import RankUpgrade from "@/component/rankUpgrade.vue";
import noTopicImg from "@/assets/meng/no_topic.png";

import { sort } from "semver";
export default {
  components: {
    topicDetails,
    RankUpgrade
  },
  data() {
    return {
      noTopicImgUrl: noTopicImg,
      activeName: "first",
      topicDetails: false,
      topicWords: "",
      TopicList: [],
      page: 1,
      count: 0,
      permissions: 1,
      needing: true,
      busy: false,
      loading: true,
      updateTime: "",
      topicId: "",
      cancel: null,
      cancel01: null,
      cancel02: null,
      cancel03: null,
      cancel04: null,
      needBuy: false,
      topicItem: {},
      showLeft: true,
      isFixed: false,
      offsetTop: 0,
      sort: 0,
      orderType: 1,
      value09: "24小时",
      vipLevel: ''
    };
  },
  computed: {
   
  },
  watch: {
    "$store.state.left_nav_flag"(old, newOld) {
      this.showLeft = newOld;
      if ((newOld = false)) {
        this.setTBBar();
      } else {
        this.setTBBar();
      }
    },
    value09(n) {
      this.page = 1;
      this.GetTopicList();
    }
  },
  created() {
    this.vipLevel = localStorage.getItem('vipLevel'); //会员等级
    let that = this;
    this.GetTopicList();
    this.$watch(
      "topicWords",
      that.debounce((newVal, oldVal) => {
        if (newVal == "") {
          that.page = 1;
          that.TopicList = [];
          that.GetTopicList();
        }
      }, 0)
    );
  },
  mounted() {
    window.addEventListener("scroll", this.initHeight);
    window.addEventListener("resize", () => {
      //给浏览器窗口绑定变化大小事件
      this.setTBBar();
    });
  },

  methods: {
    // 排序
    sort_fun(parm01, parm02) {
      if (!parm01) {
        this.sort = 1;
      } else {
        this.sort = 0;
      }
      this.orderType = parm02;

      this.page = 1;
      this.TopicList = [];
      this.GetTopicList();
    },
    // 获取子节点函数（后期可集成到一个库里）
    getChilds(pNode) {
      if (!pNode) return false;
      let nodes = pNode.childNodes;
      let newList = [];
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i];
        if (node.nodeType === 1) {
          //判断类型
          newList.push(node);
        }
      }
      return newList;
    },
    // 设置表格表头滑动置顶
    setTBBar() {
      this.$nextTick(() => {
        let tableEl = this.$refs.tableEl;
        let ulEl = this.$refs.fixedThead;
        let tr1 = document.querySelector("#tr1");
        // thTrEl.style.width = tableEl.offsetWidth+'px';
        if (tr1) {
          let tds = this.getChilds(tr1);
          let liEls = this.getChilds(ulEl);
          for (let i = 0; i < liEls.length; i++) {
            liEls[i].style.width = tds[i].offsetWidth + "px";
          }
        }
      });
    },
    GetTopicList(cpage) {
      let that = this;
      this.TopicList = [];
      if (cpage) {
        that.page = cpage;
        that.backTop();
        //console.log("page", this.page);
      }
      let time;
      switch (this.value09) {
        case "1小时":
          time = "1h";
          break;
        case "3小时":
          time = "3h";
          break;
        case "6小时":
          time = "6h";
          break;
        case "12小时":
          time = "12h";
          break;
        case "24小时":
          time = "24h";
          break;
        case "近3天":
          time = "3d";
          break;
        case "近7天":
          time = "7d";
          break;
        case "近30天":
          time = "30d";
          break;
        case "近90天":
          time = "90d";
          break;
      }
      that.loading = true;
      that.needBuy = false;
      that.busy = true;
      that.$axios
        .post(
          "/api/topic/GetTopicList",
          {
            Title: this.trimStr(that.topicWords),
            Index: that.page,
            Size: 30,
            SortValue: this.orderType,
            DateRange: time
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel != null) {
                that.cancel();
              }
              that.cancel = c;
            })
          }
        )
        .then(res => {
          that.loading = false;
          if (res.data.code1 ==1013||res.data.code == 1003||res.data.code ==1013) {
            this.permissions = 0;
            this.TopicList = [];
          } else {
            this.permissions = 1;
          }
          if (res.data.code == 0) {
            that.TopicList = res.data.data.topics;
            this.setTBBar();
            that.updateTime = res.data.data.timeSpan;

            that.count = res.data.data.totalCount;
          }
          if (res.data.code == 1002) {
            this.needing = false;
          } else {
            this.needing = true;
          }
          this.needing = true;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 收藏话题
    addStar(id, item) {
      let that = this;
      that.$axios
        .post(
          "/api/collection/InsertCollection",
          {
            CollectId: id,
            Module: 4 //模块 1达人 2视频 3音乐 4话题 5商品
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel01 != null) {
                that.cancel01();
              }
              that.cancel01 = c;
            })
          }
        )
        .then(res => {
          if (res.data.code == 0) {
            item.isCollect = 1;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 取消收藏话题
    cancelStar(id, item) {
      let that = this;
      that.$axios
        .post(
          "/api/collection/CancelCollection",
          {
            CollectId: id,
            Module: 4 //模块 1达人 2视频 3音乐 4话题 5商品
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel02 != null) {
                that.cancel02();
              }
              that.cancel02 = c;
            })
          }
        )
        .then(res => {
          if (res.data.code == 0) {
            item.isCollect = 0;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 添加视频收藏
    addVideoStar(id, item) {
      let that = this;
      that.$axios
        .post(
          "/api/collection/InsertCollection",
          {
            CollectId: id,
            Module: 2 //模块 1达人 2视频 3音乐 4话题 5商品
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel03 != null) {
                that.cancel03();
              }
              that.cancel03 = c;
            })
          }
        )
        .then(res => {
          if (res.data.code == 0) {
            item.isCollect = 1;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    backTop() {
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    },
    // 取消收藏视频
    cancelVideoStar(id, item) {
      let that = this;
      that.$axios
        .post(
          "/api/collection/CancelCollection",
          {
            CollectId: id,
            Module: 2 //模块 1达人 2视频 3音乐 4话题 5商品
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel04 != null) {
                that.cancel04();
              }
              that.cancel04 = c;
            })
          }
        )
        .then(res => {
          if (res.data.code == 0) {
            item.isCollect = 0;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    loadMore() {
      this.GetTopicList();
    },
    toSearch() {
      if (this.topicWords != "") {
        this.page = 1;
        this.TopicList = [];
        this.GetTopicList();
      }
    },
    seeDetails(id) {
      // this.topicId = topicId
      // this.topicItem = item
      // this.topicDetails = true
      let router = this.$router.resolve({
        path: `/talent_main/topicDetailsMainL/${id}`
      });
      window.open(router.href, "_blank");
    },
    playVideo(url) {
      window.open(url);
    },
    toBuy() {
      let router = this.$router.resolve({
        path: `/talent_main/buy`
      });
      window.open(router.href, "_blank");
    },
    // 在详情中收藏了话题
    changeTopicCollect(isCollect) {
      // console.log('改变收藏')
      this.topicItem.isCollect = isCollect;
    },
    // 在详情中收藏了视频
    changeVideoCollect(isCollect, id) {
      // console.log('改变收藏视频')
      this.topicItem.awemeTop3.map(item => {
        if (item.awemeId == id) {
          item.isCollect = isCollect;
        }
      });
    },
    initHeight() {
      var scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      this.isFixed = scrollTop > 180 ? true : false;
    },
    generatorImage() {
      //分享截图
      if (this.TopicList.length) {
        var that = this;
        const loading = this.$loading({
          lock: true,
          text: "导出中...",
          spinner: "el-icon-loading",
          customClass: "customClass"
        });
        var shareContent;
        shareContent = this.$refs.capture; //需要截图的包裹的（原生的）DOM 对象
        var width = shareContent.offsetWidth; //获取dom 宽度
        var height = shareContent.offsetHeight; //获取dom 高度
        var canvas = document.createElement("canvas"); //创建一个canvas节点
        //   var scale = window.devicePixelRatio //定义任意放大倍数 支持小数 //   var scale = 2 //定义任意放大倍数 支持小数
        var scale = 1;
        canvas.width = width * scale * scale; //定义canvas 宽度 * 缩放
        canvas.height = height * scale * scale; //定义canvas高度 *缩放
        canvas.style.width = width + "px";
        canvas.style.height = height + "px";
        canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
        var opts = {
          dpi: window.devicePixelRatio,
          scale: scale, // 添加的scale 参数
          useCORS: true,
          canvas: canvas, //自定义 canvas
          logging: true //日志开关
        };
        html2canvas(shareContent, opts).then(canvas => {
          let str;
          str = `《热门话题排行榜-${this.timestamp(
            new Date().getTime() / 1000,
            "Y-M-D"
          )}》.png`;
          canvas.toBlob(
            function(blob) {
              const eleLink = document.createElement("a");
              eleLink.download = str;
              eleLink.style.display = "none";
              // 字符内容转变成blob地址
              eleLink.href = URL.createObjectURL(blob);
              // 触发点击
              document.body.appendChild(eleLink);
              eleLink.click();
              // 然后移除
              document.body.removeChild(eleLink);
            },
            "image/png",
            1
          );
          loading.close();
        });
      }
    },
    export_data() {
      if (this.TopicList.length) {
        let that = this;
        let str = `话题名称,参与人数,总播放量\n`;
        for (let i = 0; i < that.TopicList.length; i++) {
          str += `${that.TopicList[i].title},${that.format_num(
            that.TopicList[i].useCount
          )},${that.format_num(that.TopicList[i].playCount)}\n`;
        }
        var blob = new Blob([str], { type: "text/plain;charset=utf-8" }); //解决中文乱码问题
        blob = new Blob([String.fromCharCode(0xfeff), blob], {
          type: blob.type
        });
        let object_url = window.URL.createObjectURL(blob);
        var link = document.createElement("a");
        link.href = object_url;
        let str_name = `《热门话题排行榜-${that.timestamp(
          new Date().getTime() / 1000,
          "Y-M-D"
        )}》.csv`;
        link.download = str_name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  }
};
